﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using OpenPop.Pop3;
using OpenPop.Mime;
using Newtonsoft.Json;
using Alfred.Ressource;
using System.Threading;

namespace Alfred
{
    class Mail
    {
        public System.Timers.Timer timerRappel { get; set; }
        public List<Message> mails { get; set; }
        public bool hasNewMails { get; set; }
        public List<Message> newMails { get; set; }
        public List<string> dlUids { get; set; }
        public List<string> seenUids { get; set; }
        public Pop3Client client { get; set; }

        public Mail()
        {
            dlUids = new List<string>();
            seenUids = new List<string>();
            client = new Pop3Client();
            mails = new List<Message>();
            newMails = new List<Message>();
        }

        public void LaunchTimer()
        {
            timerRappel = new System.Timers.Timer(10000);
            timerRappel.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
            timerRappel.Enabled = true;
        }

        public void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            getUidsFromText();
            getMailsFromText();
            getAllMails();
            getNewMailsFromText();
        }

        public void getAllMails()
		{
            try
            {
                client.Connect("pop3.live.com", 995, true);
                client.Authenticate("guillaume.jacquart@live.fr", "Ghiltoniel1");
            }
            catch (Exception) { }

            int messageCount = 0;
			// Get the number of messages in the inbox
            try {messageCount = client.GetMessageCount(); }
            catch (Exception)
            {
                return;
            }

			// We want to download all messages
			List<Message> newMessages = new List<Message>(messageCount);

			List<string> uids = client.GetMessageUids();

			// All the new messages not seen by the POP3 client
			for (int i = 0; i < uids.Count; i++)
			{
				string currentUidOnServer = uids[i];
				if (!dlUids.Contains(currentUidOnServer))
				{
                    Message unseenMessage = client.GetMessage(i + 1);
					FileStream file = new FileStream(Paths.path_mails + uids[i] + ".txt", FileMode.OpenOrCreate);
					unseenMessage.Save(file);
                    file.Dispose();
					dlUids.Add(currentUidOnServer);
				}
			}
			client.Disconnect();
			saveUidsToText(dlUids);
		}

        public void saveUidsToText(List<string> uids)
        {
            StreamWriter sw = new StreamWriter(Paths.path_dlUids, false, Encoding.Default);
            foreach (string uid in uids)
            {
                sw.WriteLine(uid);
            }
            sw.Close();
        }

        public void getUidsFromText()
        {
            StreamReader sr = new StreamReader(Paths.path_seenUids, Encoding.Default);
            string s;
            while ((s = sr.ReadLine()) != null)
            {
                seenUids.Add(s);
            }
            sr.Close();

            sr = new StreamReader(Paths.path_dlUids, Encoding.Default);
            while ((s = sr.ReadLine()) != null)
            {
                dlUids.Add(s);
            }
            sr.Close();
        }

        public void getMailsFromText()
        {
            DirectoryInfo d = new DirectoryInfo(Paths.path_mails);
            foreach (FileInfo f in d.GetFiles())
            {
                if (f.Name != "dlUids.txt" && f.Name != "seenUids.txt")
                    mails.Add(Message.Load(f));
            }
        }

        public void getNewMailsFromText()
        {
            newMails = new List<Message>();
            DirectoryInfo d = new DirectoryInfo(Paths.path_mails);
            foreach (FileInfo f in d.GetFiles())
            {
                if (f.Name != "dlUids.txt" && f.Name != "seenUids.txt" && !seenUids.Contains(f.Name.Split('.').Last()))
                {
                    newMails.Add(Message.Load(f));
                    hasNewMails = true;
                }
            }
        }

        public string getNbNewMailsString()
        {
            return string.Format("Vous avez {0} nouveaux messages.", newMails.Count);
        }

        public string getFromNewMailsString()
        {
            string s = "";
            foreach (Message mail in newMails)
            {
                s += mail.Headers.From.DisplayName + ", ";
            }
            return s;
        }

        public string getContentNewMailString(Message m)
        {
            return m.FindFirstPlainTextVersion().GetBodyAsText();
        }
    }
}
